#!/usr/bin/python

""" CLASS/MODULE:
    Purpose:
"""
__author__ = 'liwei79@gmail.com'

import getopt
import c_parse

from CodeGenerator import *
from RTL.RTLProgram import RTLProgram
import util

class CompilerOpts:
    def __init__(self, args):
        self.args = args
        self.help = 0
        self.debug = 0
        self.error = 0
        self.srcFile = ""
        self.parseArgs()

    def parseArgs(self):
        opts, args  = getopt.getopt(self.args, "hd", ["help", "debug"])
        for o, a in opts:
            if o in ("-h", "--help"):
                self.help = 1
            if o in ("-d", "--debug"):
                self.debug = 1
                util.dbg = 1
        if len(args) != 1:
            self.error = 1
        else:
            self.srcFile = args[0]

    def printHelp(self):
        print "Usage:c2v [-h|--help] [-d|--debug] <file>"
        print "=== by liwei79@gmail.com, 2007 ==="

class Compiler:
    def __init__(self, opts):
        self.opts = opts
        self.srcText = ""
        if self.opts.help or self.opts.error:
            self.opts.printHelp()
            sys.exit(1)
        self.lexer = 0
        self.parser = 0
        self.program = 0

    def setParser(self, parser):
        self.parser = parser

    def setLexer(self, lexer):
        self.lexer = lexer

    def loadSrcText(self):
        assert(self.opts.srcFile)
        srcText = open(self.opts.srcFile, "rb").read()
        return srcText

    def initCg(self):
        assert(self.lexer)
        assert(self.parser)
        srcText = self.loadSrcText()
        self.cg = CodeGenerator(self.lexer, self.parser, srcText)
        c_parse.SetCgForParser(self.cg)

    def doCg(self):
        self.program = self.cg.doParseCg()

    def getCg(self):
        return self.cg

    def __repr__(self):
        str = "Invoke compiler for src: %s \n" % self.opts.srcFile 
        str = str + repr(self.cg)
        return str

